<?php
include(dirname(__FILE__).'/../../config/config.inc.php');
include(dirname(__FILE__).'/../../header.php');
include(dirname(__FILE__).'/kreditorpartpayment.php');

require (dirname(__FILE__).'/kreditor/kreditor.php');
require (dirname(__FILE__).'/kreditor/kreditor_lang.php');

$confirm = Tools::getValue('confirm');
$addressflag = Tools::getValue('addressflag');
$products = $cart->getProducts();

$errors = "";
	
$eid = Configuration::get('KREDITOR_PP_MERCHANT_ID');
$secret = Configuration::get('KREDITOR_PP_SECRET');
$estoreUser = $customer_id;
$goodsList = array();

// Address
$deliveryaddress = new Address(intval($cart->id_address_delivery));
$invoiceaddress = new Address(intval($cart->id_address_invoice));

$deliverycountry = new Country($deliveryaddress->id_country);
$invoicecountry = new Country($invoiceaddress->id_country);

// xxx Get currency object
$curr = new Currency(intval(isset($cart->id_currency) ? $cart->id_currency : Configuration::get('PS_CURRENCY_DEFAULT')));
// xxx Convert the currency ISO code to Kreditor format

switch(strtolower($deliverycountry->iso_code))
{
	case 'se':
		$kreditor_cc = $KRED_ISO3166_SE;
		break;
	case 'dk':
		$kreditor_cc = $KRED_ISO3166_DK;
		break;
	case 'no':
		$kreditor_cc = $KRED_ISO3166_NO;
		break;
	case 'fi':
		$kreditor_cc = $KRED_ISO3166_FI;
		break;
	case 'de':
		$kreditor_cc = $KRED_ISO3166_DE;
		break;
	case 'nl':
		$kreditor_cc = $KRED_ISO3166_NL;
		break;	
}


// xxx Array to store pclasses in
$arr_pclass = array();
$kreditor = new KreditorPartPayment();
// xxx Loop through all available pclasses
foreach(get_pclass_ids() as $key => $pclass)
{
	if(correct_country($pclass, $kreditor_cc))
	{
		
		calc_monthly_cost(Tools::convertPrice($cart->getOrderTotal(true, 3)*100, $curr), $pclass, 0, $kreditor_cc, $result);
		
		if(get_type($pclass) == 1)
			$arr_pclass[] = array("pclass" => $pclass, "text" => $klarna_text = htmlentities(sprintf(get_pclass_header($key) . " - %s" . $curr->iso_code . "/" . utf8_decode($kreditor->getL('month')), ceil($result/100))), "type" => get_type($pclass));
		else if(Tools::convertPrice($cart->getOrderTotal(true, 3)*100, $curr) >= 1000) {
			$arr_pclass[] = array("pclass" => $pclass, "text" => $klarna_text = htmlentities(sprintf(get_pclass_header($key) . " - %s" . $curr->iso_code . "/" . utf8_decode($kreditor->getL('month')), ceil($result/100))), "type" => get_type($pclass));
		} else
			$arr_pclass[] = array("pclass" => $pclass, "text" => $klarna_text = get_pclass_header($key), "type" => get_type($pclass));
	}
}

// xxx Custom method to sort the array to
// make Klarna Konto appear first
function cmp($a, $b) { 
return (($a['type'] == 1) ? 0 : 1);  
} 
// xxx Sort the array using our custom method
uasort($arr_pclass, 'cmp');

if ($confirm && (empty($_POST['klarna_pclass']))) {
	$errors .= $kreditor->getL("Missing pclass");
}

if ($confirm && (empty($_POST['kreditor_telephone']) || !Validate::isPhoneNumber($_POST['kreditor_telephone']))) {
	$errors .= $kreditor->getL("Wrong telephone");
}

if ($confirm && (empty($_POST['kreditor_email']) || !Validate::isEmail($_POST['kreditor_email']))) {
	$errors .= $kreditor->getL("Wrong email");
}

$deliveryaddress = new Address(intval($cart->id_address_delivery));
$invoiceaddress = new Address(intval($cart->id_address_invoice));

$deliverycountry = new Country($deliveryaddress->id_country);
$invoicecountry = new Country($invoiceaddress->id_country);

$pno   = $_POST['kreditor_pnum'];
$pno = str_replace("-", "", $pno);
$pno = str_replace(" ", "", $pno);
$fname = $_POST['kreditor_fname'];
$lname = $_POST['kreditor_lname'];
$pclass = $_POST['klarna_pclass'];
switch($deliverycountry->iso_code) {
	case 'SE':
		$kreditor_addr = mk_addr_se("", utf8_decode($_POST['kreditor_street']),
	     	  				utf8_decode($_POST['kreditor_postno']),
	       					utf8_decode($_POST['kreditor_city']),
	       					"",
	       					utf8_decode($_POST['kreditor_telephone']),
							utf8_decode($_POST['kreditor_email']));
	break;
	
	case 'FI':
		$kreditor_addr = mk_addr_fi("", utf8_decode($_POST['kreditor_street']),
	     	  				utf8_decode($_POST['kreditor_postno']),
	       					utf8_decode($_POST['kreditor_city']),
	       					"",
	       					utf8_decode($_POST['kreditor_telephone']),
							utf8_decode($_POST['kreditor_email']));
	break;
	
		case 'NO':
		$kreditor_addr = mk_addr_no("", utf8_decode($_POST['kreditor_street']),
	     	  				utf8_decode($_POST['kreditor_postno']),
	       					utf8_decode($_POST['kreditor_city']),
	       					"",
	       					utf8_decode($_POST['kreditor_telephone']),
							utf8_decode($_POST['kreditor_email']));
	break;
	
	case 'DK':
		$kreditor_addr = mk_addr_dk("", utf8_decode($_POST['kreditor_street']),
	     	  				utf8_decode($_POST['kreditor_postno']),
	       					utf8_decode($_POST['kreditor_city']),
	       					"",
	       					utf8_decode($_POST['kreditor_telephone']),
							utf8_decode($_POST['kreditor_email']));
	break;
	
		case 'DE':
		$kreditor_addr = mk_addr_de("", utf8_decode($_POST['kreditor_street']),
	     	  				utf8_decode($_POST['kreditor_postno']),
	       					utf8_decode($_POST['kreditor_city']),
	       					"",
	       					utf8_decode($_POST['kreditor_telephone']),
							utf8_decode($_POST['kreditor_email']), utf8_decode($_POST['kreditor_house']));
	break;
	
	case 'NL':
		$kreditor_addr = mk_addr_nl("", utf8_decode($_POST['kreditor_street']),
	     	  				utf8_decode($_POST['kreditor_postno']),
	       					utf8_decode($_POST['kreditor_city']),
	       					'',
	       					utf8_decode($_POST['kreditor_telephone']),
							utf8_decode($_POST['kreditor_email']), utf8_decode($_POST['kreditor_house']), utf8_decode($_POST['kreditor_houseext']));
	break;
}



$validaddress = true;

/* If the delivery address is not the same as the invoice address, set the delivery address to the invoice address */
if (intval($cart->id_address_invoice) != intval($cart->id_address_delivery)) {
	$cart->id_address_delivery = $cart->id_address_invoice;
	$cart->save();
}

$deliveryaddress = new Address(intval($cart->id_address_delivery));
$invoiceaddress = new Address(intval($cart->id_address_invoice));

$addressfinland = false;

/* Check if delivery or invoice address is in Finland, then no
 * attempt to get_addresses will be done, because it's not allowed by Klarna.
 */
$deliverycountry = new Country($deliveryaddress->id_country);
$invoicecountry = new Country($invoiceaddress->id_country);

if (strpos("FI,NO,DE,DK,NL", $deliverycountry->iso_code) !== false ||
	(strpos("FI,NO,DE,DK,NL", $invoicecountry->iso_code) !== false)) {
	$addressfinland = true;		
}

/* Check if address is valid for the current person number (Anti-fraud detection) */
if ($confirm && !$addressflag && empty($errors) && !$addressfinland) {
    $pnoencoding = $PNO_SE;
    $type = $GA_OLD;
    
	$status = get_addresses($eid, $pno, $secret, $pnoencoding, $type, $result);
    $addrs = $result;
    if ($status != 0){      
      $errors .= strerror_se($result);
    }
	
    
    $validdelivery = false;
    $validinvoice = false;

    foreach ($addrs as $key => $addr)
	{
		$addresses[$key]['fname'] = htmlentities($addr[0]);
		$addresses[$key]['lname'] = htmlentities($addr[1]);
		$addresses[$key]['street'] = htmlentities($addr[2]);
		$addresses[$key]['postcode'] = htmlentities($addr[3]);
		$addresses[$key]['city'] =  htmlentities($addr[4]);
		
/*		echo "***".$addr[0]."***".utf8_decode(htmlspecialchars($deliveryaddress->firstname, ENT_COMPAT, "UTF-8"))."***<br />";
		echo "***".$addr[1]."***".utf8_decode(htmlspecialchars($deliveryaddress->lastname, ENT_COMPAT, "UTF-8"))."***<br />";
		echo "***".$addr[2]."***".utf8_decode(htmlspecialchars($deliveryaddress->address1, ENT_COMPAT, "UTF-8"))."***<br />";
		echo "***".$addr[3]."***".utf8_decode(htmlspecialchars($deliveryaddress->postcode, ENT_COMPAT, "UTF-8"))."***<br />";
		echo "***".$addr[4]."***".utf8_decode(htmlspecialchars($deliveryaddress->city, ENT_COMPAT, "UTF-8"))."***<br />";
		echo stristr($addr[0], utf8_decode(htmlspecialchars($deliveryaddress->firstname, ENT_COMPAT, "UTF-8")))."<br />";
		echo strcasecmp($addr[1], utf8_decode(htmlspecialchars($deliveryaddress->lastname, ENT_COMPAT, "UTF-8")))."<br />";
		echo strcasecmp($addr[2], utf8_decode(htmlspecialchars($deliveryaddress->address1, ENT_COMPAT, "UTF-8")))."<br />";
		echo strcasecmp($addr[3], utf8_decode(htmlspecialchars($deliveryaddress->postcode, ENT_COMPAT, "UTF-8")))."<br />";
		echo strcasecmp($addr[4], utf8_decode(htmlspecialchars($deliveryaddress->city, ENT_COMPAT, "UTF-8")))."<br />";
				
		echo "***".$addr[0]."***".utf8_decode(htmlspecialchars($invoiceaddress->firstname, ENT_COMPAT, "UTF-8"))."***<br />";
		echo "***".$addr[1]."***".utf8_decode(htmlspecialchars($invoiceaddress->lastname, ENT_COMPAT, "UTF-8"))."***<br />";
		echo "***".$addr[2]."***".utf8_decode(htmlspecialchars($invoiceaddress->address1, ENT_COMPAT, "UTF-8"))."***<br />";
		echo "***".$addr[3]."***".utf8_decode(htmlspecialchars($invoiceaddress->postcode, ENT_COMPAT, "UTF-8"))."***<br />";
		echo "***".$addr[4]."***".utf8_decode(htmlspecialchars($invoiceaddress->city, ENT_COMPAT, "UTF-8"))."***<br />";
		echo stristr($addr[0], utf8_decode(htmlspecialchars($invoiceaddress->firstname, ENT_COMPAT, "UTF-8")))."<br />";
		echo strcasecmp($addr[1], utf8_decode(htmlspecialchars($invoiceaddress->lastname, ENT_COMPAT, "UTF-8")))."<br />";
		echo strcasecmp($addr[2], utf8_decode(htmlspecialchars($invoiceaddress->address1, ENT_COMPAT, "UTF-8")))."<br />";
		echo strcasecmp($addr[3], utf8_decode(htmlspecialchars($invoiceaddress->postcode, ENT_COMPAT, "UTF-8")))."<br />";
		echo strcasecmp($addr[4], utf8_decode(htmlspecialchars($invoiceaddress->city, ENT_COMPAT, "UTF-8")))."<br />";
*/		
		/* Check if delivery- and invoice addresses are valid */
		if (stristr($addr[0], utf8_decode(htmlspecialchars($deliveryaddress->firstname, ENT_COMPAT, "UTF-8"))) != FALSE && /* One of the firstnames is enough */
			strcasecmp($addr[1], utf8_decode(htmlspecialchars($deliveryaddress->lastname, ENT_COMPAT, "UTF-8"))) == 0 &&
			strcasecmp($addr[2], utf8_decode(htmlspecialchars($deliveryaddress->address1, ENT_COMPAT, "UTF-8"))) == 0 &&
			strcasecmp($addr[3], utf8_decode(htmlspecialchars($deliveryaddress->postcode, ENT_COMPAT, "UTF-8"))) == 0 &&
			strcasecmp($addr[4], utf8_decode(htmlspecialchars($deliveryaddress->city, ENT_COMPAT, "UTF-8") == 0))) {
			$validdelivery = true;		
		}
		
		if (stristr($addr[0], utf8_decode(htmlspecialchars($invoiceaddress->firstname, ENT_COMPAT, "UTF-8"))) != FALSE && /* One of the firstnames is enough */
			strcasecmp($addr[1], utf8_decode(htmlspecialchars($invoiceaddress->lastname, ENT_COMPAT, "UTF-8"))) == 0 &&
			strcasecmp($addr[2], utf8_decode(htmlspecialchars($invoiceaddress->address1, ENT_COMPAT, "UTF-8"))) == 0 &&
			strcasecmp($addr[3], utf8_decode(htmlspecialchars($invoiceaddress->postcode, ENT_COMPAT, "UTF-8"))) == 0 &&
			strcasecmp($addr[4], utf8_decode(htmlspecialchars($invoiceaddress->city, ENT_COMPAT, "UTF-8"))) == 0) {
			$validinvoice = true;		
		}
	}

	/* Address is valid if both delivery and invoice addresses are valid */
	$validaddress = $validinvoice && $validdelivery;
	
	/*
	echo "VALIDDELIVERY: ".($validdelivery ? "TRUE" : "FALSE")."<br />";
	echo "VALIDINVOICE: ".($validinvoice ? "TRUE" : "FALSE")."<br />";
	echo "VALIDADDRESS: ".($validaddress ? "TRUE" : "FALSE")."<br />";
	*/
}


$addressnr = $_POST["adressnr"];

/* Set order delivery and invoice address to the address chosen */
if ($confirm && 
	$addressflag && 
	empty($errors) &&
	$addressnr > 0 &&
	!$addressfinland) {
		
    $pnoencoding = $PNO_SE;
    $type = $GA_OLD;
	
	/* Get the address with the specified number */
	$status = get_addresses($eid, $pno, $secret, $pnoencoding, $type, $result);
    $addrs = $result;
    if ($status != 0){      
      $errors .= strerror_se($result);
    }
	else {	
		/* Set the delivery address of the order to the chosen address */
		
		/* If there is no first name, the last name is assumed to be a company name */
		if (empty($addrs[$addressnr-1][0])) {
	    	$deliveryaddress->firstname = utf8_encode($addrs[$addressnr-1][1]);
	    	$deliveryaddress->companyname = utf8_encode($addrs[$addressnr-1][1]);
		} 
		else {
	    	$deliveryaddress->firstname = utf8_encode($addrs[$addressnr-1][0]);
			if (!empty($addrs[$addressnr-1][1]))
	    		$deliveryaddress->lastname = utf8_encode($addrs[$addressnr-1][1]);
		}
		
		if (!empty($addrs[$addressnr-1][2]))
	    	$deliveryaddress->address1 = utf8_encode($addrs[$addressnr-1][2]);
	    $deliveryaddress->postcode = utf8_encode($addrs[$addressnr-1][3]);
	    $deliveryaddress->city = utf8_encode($addrs[$addressnr-1][4]);
	    $deliveryaddress->save();
	    
		/* Set the invoice address of the order to the chosen address */
		
		/* If there is no first name, the last name is assumed to be a company name */
	    if (empty($addrs[$addressnr-1][0])) {
	    	$invoiceaddress->firstname = utf8_encode($addrs[$addressnr-1][1]);
	    	$invoiceaddress->companyname = utf8_encode($addrs[$addressnr-1][1]);
		} 
		else {
	    	$invoiceaddress->firstname = utf8_encode($addrs[$addressnr-1][0]);
			if (!empty($addrs[$addressnr-1][1]))
	    		$invoiceaddress->lastname = utf8_encode($addrs[$addressnr-1][1]);
		}
		
	    if (!empty($addrs[$addressnr-1][2]))
	    	$invoiceaddress->address1 = utf8_encode($addrs[$addressnr-1][2]);
	    $invoiceaddress->postcode = utf8_encode($addrs[$addressnr-1][3]);
	    $invoiceaddress->city = utf8_encode($addrs[$addressnr-1][4]);
	    $invoiceaddress->save();
	    
	    $fname = utf8_decode($invoiceaddress->firstname);
	    $lname = utf8_decode($invoiceaddress->lastname);
	    $KREDITOR_PP_addr = mk_addr_se("", utf8_decode($invoiceaddress->address1),
	       					utf8_decode($invoiceaddress->postcode),
	       					utf8_decode($invoiceaddress->city),
	       					"",$_POST['KREDITOR_PP_telephone'], $_POST['KREDITOR_PP_email']);
	}    
}

/* Validate order */
if ($confirm && 
	empty($errors) &&
	$validaddress)
{
	$n = sizeof($products);
	
	// First all the ordinary items
	for ($i = 0 ; $i < $n ; $i++) {
		// Get the price inc. tax for the current currency
		$price_with_tax = Tools::convertPrice($products[$i]['price_wt'], $currency) * 100;
		$attributes = "";
	    
		if(isset($products[$i]['attributes'])){
			$attributes = $products[$i]['attributes'];
		}
	
		$goodsList[] =
				mk_goods_flags($products[$i]['cart_quantity'],
						$products[$i]['id_product'],
						strip_tags(utf8_decode($products[$i]['name'] . $attributes)),
						$price_with_tax,
						$products[$i]['rate'],
						0, 32);
	}
	
	// xxx Get the discounts
	$discounts = $cart->getDiscounts();
	// xxx We use the same tax on the discounts as on the invoice fee
	$disctaxobj = new Tax(intval(Configuration::get('KREDITOR_PP_TAX_CLASS_' . $deliverycountry->iso_code)), intval($id_lang));
	$disctax = $disctaxobj->rate;
	// xxx Subtract the sum from the coupons.
	for($i = 0; $i < sizeof($discounts); $i++)
	{
		$goodsList[] =
				mk_goods_flags(1,
						"",
						strip_tags(utf8_decode($discounts[$i]['description'])),
						Tools::convertPrice(floatval($discounts[$i]['value_real']*100*(-1)), $currency),
						floatval($disctax),
						0,32);
	}
	
	
    $estoreOrderNo = "";
    $shipmentfee = Tools::convertPrice($cart->getOrderShippingCost(), $currency) * 100;
    $shipmenttype = 1;
    $handlingfee = 0;
    $ready_date = "";
	

		
	if ($shipmentfee > 0.0) {
		$carrier = new Carrier((isset($cart->id_carrier) && !empty($cart->id_carrier)) ? intval($cart->id_carrier) : Configuration::get('PS_CARRIER_DEFAULT'));
		if (!Validate::isLoadedObject($carrier))
			die(Tools::displayError('Hack attempt: "no default carrier"'));
        if ($carrier->active) {
			$taxobj = new Tax(intval($carrier->id_tax), intval($id_lang));
			$tax = $shipmentfee-$shipmentfee*100/(100+$taxobj->rate);

			$price_with_tax = $shipmentfee;
			
			$goodsList[] = mk_goods_flags(1, "", utf8_decode($kreditor->getL('Shipping fee')), $price_with_tax, $taxobj->rate, 0, 40);
        }
	}
	    	
	// xxx Add the fee for gift wrapping to the invoice
	if($cart->gift)
	{
		$wrappingTax = new Tax(Configuration::get('PS_GIFT_WRAPPING_TAX'));
		$goodsList[] = mk_goods_flags(1, "", utf8_decode($kreditor->getL('Gift wrapping fee')), Tools::convertPrice(floatval(Configuration::get('PS_GIFT_WRAPPING_PRICE')), $currency)*100, $wrappingTax->rate, 0, 32);		
	}
		
    $passwd = "";
    $clientIp = $_SERVER["REMOTE_ADDR"];
    $newPasswd = "";
		
	if (Configuration::get('KREDITOR_PP_TESTFLAG') == '1') {
		$flags = $KRED_TEST_MODE;
    } else {
		$flags = 0;
    }

switch($deliverycountry->iso_code) {
	case 'SE':
		$status =
	      add_transaction_se($eid, $estoreUser, $secret, $estoreOrderNo,
			     $goodsList, 0, $shipmenttype,
			     $handlingfee, $pno, $fname, $lname, $kreditor_addr,
			     $passwd, $clientIp, "", $flags, $comment, $ready_date, "", $_POST['klarna_pclass'], 0, $result);
	break;
	
	case 'FI':
		$status =
	      add_transaction_fi($eid, $estoreUser, $secret, $estoreOrderNo,
			     $goodsList, 0, $shipmenttype,
			     $handlingfee, $pno, $fname, $lname, $kreditor_addr,
			     $passwd, $clientIp, "", $flags, $comment, $ready_date, "", $_POST['klarna_pclass'], 0, $result);
	break;
	
	case 'NO':
		$status =
	      add_transaction_no($eid, $estoreUser, $secret, $estoreOrderNo,
			     $goodsList, 0, $shipmenttype,
			     $handlingfee, $pno, $fname, $lname, $kreditor_addr,
			     $passwd, $clientIp, "", $flags, $comment, $ready_date, "", $_POST['klarna_pclass'], 0, $result);
	break;
	
	case 'DK':
		$status =
	      add_transaction_dk($eid, $estoreUser, $secret, $estoreOrderNo,
			     $goodsList, 0, $shipmenttype,
			     $handlingfee, $pno, $fname, $lname, $kreditor_addr,
			     $passwd, $clientIp, "", $flags, $comment, $ready_date, "", $_POST['klarna_pclass'], 0, $result);
	break;
	
	case 'DE':
		$status =
	      add_transaction_de($eid, $estoreUser, $secret, $estoreOrderNo,
			     $goodsList, 0, $shipmenttype,
			     $handlingfee, $pno . $_POST['klarna_gender'], $fname, $lname, $kreditor_addr,
			     $passwd, $clientIp, "", $flags, $comment, $ready_date, "", $_POST['klarna_pclass'], 0, $result);
	break;
	
	case 'NL':
		$status =
	      add_transaction_nl($eid, $estoreUser, $secret, $estoreOrderNo,
			     $goodsList, 0, $shipmenttype,
			     $handlingfee, $pno . $_POST['klarna_gender'], $fname, $lname, $kreditor_addr,
			     $passwd, $clientIp, "", $flags, $comment, $ready_date, "", -1, 0, $result);
	break;
	
	default:
	$status = -1;
	$result = "Incorrect country";
	break;
}	
    
	
    if ($status == 0){
		$kreditor->validateOrder($cart->id, _PS_OS_PAYMENT_, $cart->getOrderTotal(true, 3), $kreditor->displayName, $kreditor->getL('transaction').$result);
		$order = new Order(intval($kreditor->currentOrder));
			
		/* Update kreditor invoice with order number */
		$invno = $result;
		update_orderno($eid, $invno, $secret, $kreditor->currentOrder, $result);
			
		Tools::redirectLink(__PS_BASE_URI__.'order-confirmation.php?id_cart='.intval($cart->id).'&id_module='.intval($kreditor->id).'&id_order='.intval($kreditor->currentOrder));
    } else {
			$errors .= $result;
    }    
} 

/* or ask for confirmation */ 
	
$address = new Address(intval($cart->id_address_invoice));
$customer = new Customer(intval($cart->id_customer));
$currency = new Currency(intval(isset($cart->id_currency) ? $cart->id_currency : Configuration::get('PS_CURRENCY_DEFAULT')));
$ordertotal = Tools::convertPrice($cart->getOrderTotal(true, 3), $currency);

/*
 * Order value may NOT excede the credit limit.
 */
 
if ($ordertotal > Tools::convertPrice(floatval(Configuration::get('KREDITOR_PP_ORDER_LIMIT')), $currency))
	return $this->l('Klarna error: (Order value exceeds the credit limit)');	

	
	
if (!Validate::isLoadedObject($address) OR !Validate::isLoadedObject($customer) OR !Validate::isLoadedObject($currency))
	return $this->l('Klarna error: (invalid address or customer)');
		
$products = $cart->getProducts();
	
foreach ($products as $key => $product)
{
	$products[$key]['name'] = str_replace('"', '\'', $product['name']);
	if (isset($product['attributes']))
		$products[$key]['attributes'] = str_replace('"', '\'', $product['attributes']);
	$products[$key]['name'] = htmlentities(utf8_decode($product['name']));
	$products[$key]['KreditorAmount'] = number_format(Tools::convertPrice($product['price_wt'], $currency), 2, '.', '');
}

$pno = "";
if ((Configuration::get('KREDITOR_PP_PRE_POPULATE') == 1)) {
	$pno = date("ymd", strtotime($customer->birthday));
}

$telephone = $address->phone_mobile;

$email = $customer->email;

if ($confirm) {
	$pno = $_POST['kreditor_pnum'];
	$telephone = $_POST['kreditor_telephone'];
	$email = $_POST['kreditor_email'];
	$pclass = $_POST['klarna_pclass'];
}
$country = new Country(intval($address->id_country));

if(strtolower($country->iso_code) == "de" || strtolower($country->iso_code) == "nl") {
$addr_array = explode(" ", $address->address1);
			if(sizeof($addr_array) > 1)
				$housenum = array_pop($addr_array);
			else
				$housenum = "";
				
			$address->address1 = implode($addr_array, " ");
			$address->housenum = $housenum;
}

$smarty->assign(array(
			'address' => $address,
			'addresses' => $addresses,
			'eid' => $eid,
			'country' => $country,
			'customer' => $customer,
			'currency' => $currency,
			'pno' => $pno,
			'telephone' => $telephone,
			'email' => $email,
			'amount' => number_format(Tools::convertPrice($cart->getOrderTotal(true, 4), $currency), 2, '.', ''),
			'shipping' =>  number_format((Tools::convertPrice(($cart->getOrderShippingCost() + $cart->getOrderTotal(true, 6)), $currency)), 2, '.', ''),
			'discounts' => $cart->getDiscounts(),
			'products' => $products,
			'total' => number_format(Tools::convertPrice($cart->getOrderTotal(true, 3), $currency), 2, '.', ''),
			'id_cart' => intval($cart->id),
//			'this_path' => $this->_path,
			'currency_default' => new Currency(Configuration::get('PS_CURRENCY_DEFAULT')),
			'total' => number_format($cart->getOrderTotal(true, 3), 2, '.', ''),
			'errors' => htmlentities($errors),
			'this_path_ssl' => (Configuration::get('PS_SSL_ENABLED') ? 'https://' : 'http://').htmlspecialchars($_SERVER['HTTP_HOST'], ENT_COMPAT, 'UTF-8').__PS_BASE_URI__.'modules/kreditorpartpayment/',
			'pclasses' => $arr_pclass,
			'selected_pclass' => $pclass
	));
	
$smarty->assign('this_path', __PS_BASE_URI__.'modules/kreditorpartpayment/');

if ($validaddress || !empty($errors)) {
	echo Module::display(__FILE__, 'validation.tpl');
}
else {
	echo Module::display(__FILE__, 'validadr.tpl');
}


include(dirname(__FILE__).'/../../footer.php');

?>
